package tk.xboot.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import tk.xboot.ws.conf.WsContextProvider;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint(value = "/wx/{xid}",configurator = WsContextProvider.class)
public class WsEndPoint {

    private Object obj = new Object();

    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam("xid") String uid) {
        System.out.println(">>>"+Thread.currentThread().getId());
        String token = (String)config.getUserProperties().get("Author");
        System.out.println(token);

        // this.request = (HttpServletRequest) config.getUserProperties().get("httpRequest");
        // this.response = (HttpServletResponse) config.getUserProperties().get("httpResponse");
        // this.session = (HttpSession) config.getUserProperties().get("httpSession");

        //session.setMaxBinaryMessageBufferSize(WebSocketConf.Server.Request.Websocket.maxBinaryMessageSize);
        //session.setMaxTextMessageBufferSize(WebSocketConf.Server.Request.Websocket.maxTextMessageSize);
        //session.setMaxIdleTimeout(WebSocketConf.Server.Request.Websocket.maxIdleTimeout);

        ServerEndpointConfig sCfg = (ServerEndpointConfig) config; //cast
        WsContextProvider wsp = (WsContextProvider)sCfg.getConfigurator();
        Map map = wsp.getUserTokens();

        map.forEach((k,v)->{
            System.out.println(">>> key:" + k +" value:" + v.toString());
        });
        session.getUserProperties();
        synchronized (obj) {    // synchronized needed.
            log.info("UID:{}",uid);
        }
        log.info("session is open");
    }

    @OnMessage
    public void onMessage(Session session,String message){
        log.info("Get message from client: {}",message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason){
        log.info(session.getClass().getName());
        System.out.println("^^^^^^" + Thread.currentThread().getId());
        log.info("Close the web socket client:{}",session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable){

    }
}
